package cn.cdeden.aiqa.service.impl;

import cn.cdeden.aiqa.domain.bo.Message;
import cn.cdeden.aiqa.domain.bo.RequestData;
import cn.cdeden.aiqa.service.OllamaService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class OllamaServiceImpl implements OllamaService {

    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    @Override
    public Flux<String> chatWithOllama(String url, String model, List<Message> history) {
        // 根据传入的 URL, model 和 messages 参数进行流式对话
        String ollamaUrl = url + "/api/chat"; // 拼接完整的 API URL

        // 构建请求体
        RequestData requestData = new RequestData(model, history, true);

        return webClient.post()
            .uri(ollamaUrl)
            .contentType(MediaType.APPLICATION_JSON)
//            .accept(MediaType.TEXT_EVENT_STREAM)
            .bodyValue(requestData)
            .retrieve()
            .bodyToFlux(String.class)
            .doOnError(ex -> {
                // 打印详细错误信息
                System.out.println("WebClient 请求发生错误: " + ex.getMessage());
                if (ex instanceof WebClientResponseException) {
                    WebClientResponseException responseException = (WebClientResponseException) ex;
                    // 打印响应状态码和响应体
                    System.out.println("响应状态码: " + responseException.getRawStatusCode());
                    System.out.println("响应体: " + responseException.getResponseBodyAsString());
                } else if (ex instanceof WebClientRequestException) {
                    WebClientRequestException requestException = (WebClientRequestException) ex;
                    // 打印请求异常的信息
                    System.out.println("请求异常: " + requestException.getMessage());
                }
            })
            .onErrorResume(ex -> {
                String errorMessage = "An error occurred: " + ex.getMessage();
                return Flux.just(errorMessage); // 返回错误信息
            });
    }

}
